<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单状态机流程图</title>
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #e0e0e0;
            padding-bottom: 20px;
        }
        .header h1 {
            color: #333;
            margin: 0;
        }
        .header p {
            color: #666;
            margin: 10px 0 0 0;
        }
        .controls {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .control-group {
            margin-bottom: 15px;
        }
        .control-group label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
            color: #333;
        }
        .control-group input, .control-group select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        .btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn-success {
            background: #28a745;
        }
        .btn-success:hover {
            background: #1e7e34;
        }
        .btn-danger {
            background: #dc3545;
        }
        .btn-danger:hover {
            background: #c82333;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }
        .result.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .result.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .state-info {
            background: #e9ecef;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .state-info h3 {
            margin-top: 0;
            color: #495057;
        }
        .valid-events {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        .event-tag {
            background: #007bff;
            color: white;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
        }
        .diagram-container {
            margin-top: 20px;
            text-align: center;
        }
        .mermaid {
            background: white;
            border-radius: 5px;
            padding: 20px;
        }
    </style>
</script>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>订单状态机流程图</h1>
            <p>可视化订单状态转换和事件处理</p>
        </div>

        <div class="controls">
            <div class="control-group">
                <label>订单ID:</label>
                <input type="number" id="orderId" value="1" placeholder="请输入订单ID">
            </div>
            <div class="control-group">
                <label>操作员ID:</label>
                <input type="text" id="operatorId" value="operator_001" placeholder="请输入操作员ID">
            </div>
            <div class="control-group">
                <label>操作员类型:</label>
                <select id="operatorType">
                    <option value="agent">代理商</option>
                    <option value="landlord">房东</option>
                    <option value="admin">管理员</option>
                </select>
            </div>
            <div class="control-group">
                <label>事件:</label>
                <select id="event">
                    <option value="accept">接单</option>
                    <option value="reject">拒绝</option>
                    <option value="assign">分配</option>
                    <option value="start">开始</option>
                    <option value="complete">完成</option>
                    <option value="cancel">取消</option>
                    <option value="suspend">暂停</option>
                    <option value="resume">恢复</option>
                    <option value="terminate">终止</option>
                    <option value="reopen">重新开启</option>
                </select>
            </div>
            <div class="control-group">
                <label>原因:</label>
                <input type="text" id="reason" placeholder="请输入操作原因">
            </div>
            <div class="control-group">
                <button class="btn" onclick="getStateInfo()">获取状态信息</button>
                <button class="btn btn-success" onclick="validateTransition()">验证转换</button>
                <button class="btn btn-danger" onclick="executeTransition()">执行转换</button>
                <button class="btn" onclick="getStateHistory()">获取历史</button>
                <button class="btn" onclick="showDiagram()">显示流程图</button>
            </div>
        </div>

        <div id="stateInfo" class="state-info" style="display: none;">
            <h3>订单状态信息</h3>
            <div id="stateInfoContent"></div>
        </div>

        <div id="result" class="result">
            <div id="resultContent"></div>
        </div>

        <div id="diagram" class="diagram-container" style="display: none;">
            <h3>状态机流程图</h3>
            <div class="mermaid" id="mermaidDiagram"></div>
        </div>
    </div>

    <script>
        // 初始化Mermaid
        mermaid.initialize({ startOnLoad: false });

        // API基础URL
        const API_BASE = 'http://127.0.0.1:8080/v1/state-machine';

        // 获取状态信息
        async function getStateInfo() {
            const orderId = document.getElementById('orderId').value;
            if (!orderId) {
                showResult('请输入订单ID', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/state-info?order_id=${orderId}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    const stateInfo = data.data;
                    document.getElementById('stateInfoContent').innerHTML = `
                        <p><strong>当前状态:</strong> ${stateInfo.state_name} (${stateInfo.current_state})</p>
                        <p><strong>可执行事件:</strong></p>
                        <div class="valid-events">
                            ${stateInfo.valid_events.map(event => `<span class="event-tag">${event}</span>`).join('')}
                        </div>
                    `;
                    document.getElementById('stateInfo').style.display = 'block';
                    showResult('获取状态信息成功', 'success');
                } else {
                    showResult(data.message, 'error');
                }
            } catch (error) {
                showResult('请求失败: ' + error.message, 'error');
            }
        }

        // 验证状态转换
        async function validateTransition() {
            const orderId = document.getElementById('orderId').value;
            const event = document.getElementById('event').value;
            
            if (!orderId || !event) {
                showResult('请输入订单ID和选择事件', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/validate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        order_id: parseInt(orderId),
                        event: event
                    })
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    const result = data.data;
                    if (result.can_transition) {
                        showResult(`状态转换有效: ${result.from_state_name} → ${result.to_state_name}`, 'success');
                    } else {
                        showResult(`状态转换无效: 无法从 ${result.from_state_name} 执行事件 ${event}`, 'error');
                    }
                } else {
                    showResult(data.message, 'error');
                }
            } catch (error) {
                showResult('请求失败: ' + error.message, 'error');
            }
        }

        // 执行状态转换
        async function executeTransition() {
            const orderId = document.getElementById('orderId').value;
            const event = document.getElementById('event').value;
            const operatorId = document.getElementById('operatorId').value;
            const operatorType = document.getElementById('operatorType').value;
            const reason = document.getElementById('reason').value;
            
            if (!orderId || !event || !operatorId) {
                showResult('请填写必要信息', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/transition`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        order_id: parseInt(orderId),
                        event: event,
                        operator_id: operatorId,
                        operator_type: operatorType,
                        reason: reason || '状态转换'
                    })
                });
                const data = await response.json();
                
                if (data.code === 200) {
                    const result = data.data;
                    showResult(`状态转换成功: ${result.from_state} → ${result.to_state} (${result.event})`, 'success');
                    // 刷新状态信息
                    setTimeout(getStateInfo, 1000);
                } else {
                    showResult(data.message, 'error');
                }
            } catch (error) {
                showResult('请求失败: ' + error.message, 'error');
            }
        }

        // 获取状态历史
        async function getStateHistory() {
            const orderId = document.getElementById('orderId').value;
            if (!orderId) {
                showResult('请输入订单ID', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/history?order_id=${orderId}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    const history = data.data.history;
                    let historyHtml = '<h4>状态变更历史:</h4><ul>';
                    history.forEach(item => {
                        historyHtml += `<li>${item.state_name} (${item.event_name}) - ${item.operator_id} - ${item.timestamp}</li>`;
                    });
                    historyHtml += '</ul>';
                    showResult(historyHtml, 'success');
                } else {
                    showResult(data.message, 'error');
                }
            } catch (error) {
                showResult('请求失败: ' + error.message, 'error');
            }
        }

        // 显示流程图
        async function showDiagram() {
            try {
                const response = await fetch(`${API_BASE}/diagram`);
                const data = await response.json();
                
                if (data.code === 200) {
                    // 显示Mermaid流程图
                    const diagramCode = `
                        stateDiagram-v2
                            [*] --> 待确认: 创建订单
                            
                            待确认 --> 已确认: 接单(accept)
                            待确认 --> 已拒绝: 拒绝(reject)
                            待确认 --> 已分配: 分配(assign)
                            待确认 --> 已取消: 取消(cancel)
                            
                            已分配 --> 已确认: 接单(accept)
                            已分配 --> 已拒绝: 拒绝(reject)
                            已分配 --> 已取消: 取消(cancel)
                            
                            已拒绝 --> 待确认: 重新开启(reopen)
                            已拒绝 --> 已取消: 取消(cancel)
                            
                            已确认 --> 进行中: 开始(start)
                            已确认 --> 已取消: 取消(cancel)
                            已确认 --> 已暂停: 暂停(suspend)
                            
                            进行中 --> 已完成: 完成(complete)
                            进行中 --> 已取消: 取消(cancel)
                            进行中 --> 已暂停: 暂停(suspend)
                            进行中 --> 已终止: 终止(terminate)
                            
                            已暂停 --> 进行中: 恢复(resume)
                            已暂停 --> 已取消: 取消(cancel)
                            已暂停 --> 已终止: 终止(terminate)
                            
                            已完成 --> 已退款: 退款(refund)
                            
                            已取消 --> 待确认: 重新开启(reopen)
                            已终止 --> 待确认: 重新开启(reopen)
                            
                            已退款 --> [*]
                    `;
                    
                    document.getElementById('mermaidDiagram').innerHTML = diagramCode;
                    document.getElementById('diagram').style.display = 'block';
                    mermaid.init(undefined, document.getElementById('mermaidDiagram'));
                    showResult('流程图加载成功', 'success');
                } else {
                    showResult(data.message, 'error');
                }
            } catch (error) {
                showResult('请求失败: ' + error.message, 'error');
            }
        }

        // 显示结果
        function showResult(message, type) {
            const resultDiv = document.getElementById('result');
            const resultContent = document.getElementById('resultContent');
            
            resultContent.innerHTML = message;
            resultDiv.className = `result ${type}`;
            resultDiv.style.display = 'block';
            
            // 3秒后自动隐藏
            setTimeout(() => {
                resultDiv.style.display = 'none';
            }, 3000);
        }

        // 页面加载时显示流程图
        window.onload = function() {
            showDiagram();
        };
    </script>
</body>
</html>

